package framework.dao
{
	
import com.adobe.serialization.json.JSON;

import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.getDefinitionByName;
import utils.URLUtil;

public class DataLoader extends URLLoader
{
	public var uid:String;
	
	public var url:String;
	
	public var dataRefName:String;
	
	public var dataRef:Class;
	
	public var dataObject:*;
	
	public function start():void
	{
		if (!dataRefName && !dataRef)
		{
			throw new IllegalOperationError("Unable to start loading data. " +
										     "The necessary property [dataRefName] and [dataRef] are Null.");
			return;
		}
		
		this.addEventListener(Event.COMPLETE, dataCompletedHandler, false, 100);
		this.load(URLUtil.getRequest(url));
	}
	
	public function dispose():void
	{
		this.removeEventListener(Event.COMPLETE, dataCompletedHandler);
		try
		{
			this.close();
		}
		catch (error:Error)
		{
			
		}
	}
	
	protected function dataCompletedHandler(event:Event):void
	{
		this.removeEventListener(Event.COMPLETE, dataCompletedHandler);
		var objClass:Class = dataRef;
		if (!objClass)
		{
			objClass = getDefinitionByName(dataRefName) as Class;
		}
		dataObject = EntryUtil.mapping(JSON.decode(this.data), objClass);
	}
}
}


